using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using ExamServer.Entities;
using ExamServer.Models;
using ExamServer.Service;
using Microsoft.AspNetCore.Mvc;

namespace ExamServer.Controllers
{
  [ApiController]
  [Route("[controller]")]
  public class RolesController : ControllerBase
  {
    private readonly IRepositoryWrapper wrapper;
    private readonly IMapper mapper;

    public RolesController(IRepositoryWrapper wrapper,
                          IMapper mapper)
    {
      this.wrapper = wrapper;
      this.mapper = mapper;
    }
    [HttpGet]
    public async Task<IActionResult> Get()
    {
      var list = await wrapper.Roles.GetAllAsync();
      if (list == null)
      {
        return NotFound();
      }
      return  new JsonResult(new
      {
        total = list.Count(),
        rows = list.ToList()
      });
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetById(int id){
      var entity = await wrapper.Roles.GetRolesById(id);
      if(entity==null){
        return NotFound();
      }
      var model = mapper.Map<RoleOptModel>(entity);
      return Ok(model);
    }

    [HttpPost]
    public async Task<IActionResult> Add([FromForm]RoleOptModel model ){    
      List<tbRolesAndMenus> list=new List<tbRolesAndMenus>();
      if(!string.IsNullOrEmpty(model.mtree)){
        var arr= model.mtree.Split(",");
        foreach(var x in arr){
          list.Add(new tbRolesAndMenus(){
            MenuID=int.Parse(x)
          });
        }
      }
      
      var roleenity = new tbRoles{
        RoleName =model.RoleName,
        RoleState=(StateEnum)Enum.Parse(typeof(StateEnum), model.StateDisplay),
        RolesAndMenus=list
      };
      wrapper.Roles.Creatre(roleenity);
      bool bl= await wrapper.Roles.SaveAsync();
      return new JsonResult(new{
        status=bl,
        message=bl?"添加成功":"添加失败"
      });
    }

    [HttpPut]
    public async Task<IActionResult> Update([FromForm]RoleOptModel model){
      var entity = await wrapper.Roles.GetRolesById(model.ID);
      entity.RoleName=model.RoleName;
      entity.RoleState=(StateEnum)Enum.Parse(typeof(StateEnum),model.StateDisplay);
      List<tbRolesAndMenus> list =new List<tbRolesAndMenus>();
      if(!string.IsNullOrEmpty(model.mtree)){
        var arr= model.mtree.Split(",");
        foreach(var x in arr){
          list.Add(new tbRolesAndMenus(){
            MenuID=int.Parse(x)
          });
        }
      }
      entity.RolesAndMenus=list;
      wrapper.Roles.Update(entity);
      bool bl = await wrapper.Roles.SaveAsync();      
      return new JsonResult(new{
        status=bl,
        message=bl?"编辑成功":"编辑失败"
      });
    }

    [HttpDelete]
    public async Task<IActionResult> Delete([FromForm]int id)
    {
      var entity = await wrapper.Roles.GetByIdAsync(id);
      if (entity == null)
      {
        return BadRequest();
      }
      entity.RoleState = 3 - entity.RoleState;//可用不可用来回切换 old:1-->new:2 old:2--->new:1
      wrapper.Roles.Update(entity);
      bool bl = await wrapper.Roles.SaveAsync();
      return new JsonResult(new
      {
        status = bl,
        message = bl ? "操作成功" : "操作失败"
      });
    }
  }
}